package com.ruikong.dazhi.controller.basicinfo;

import com.github.pagehelper.PageInfo;
import com.ruikong.dazhi.controller.result.BaseResult;
import com.ruikong.dazhi.controller.result.ResultApi;
import com.ruikong.dazhi.entity.basicinfo.Device;
import com.ruikong.dazhi.entity.basicinfo.Stock;
import com.ruikong.dazhi.model.input.DevicePageInput;
import com.ruikong.dazhi.model.input.StockPageInput;
import com.ruikong.dazhi.model.output.DeviceOutput;
import com.ruikong.dazhi.model.output.PersonnelOutput;
import com.ruikong.dazhi.service.basicinfo.IDeviceService;
import com.ruikong.dazhi.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * (Device)表控制层
 *
 * @author HuaJiaYi
 * @since 2021-09-29 10:55:42
 */
@RestController
@RequestMapping("/data")
@EnableAutoConfiguration
@Api(tags = "设备")
public class DeviceController {
    private static final Logger logger = LoggerFactory.getLogger(DeviceController.class);
    /**
     * 服务对象
     */
    @Autowired
    private IDeviceService deviceService;

    @PostMapping("/getDeviceById")
    @ApiOperation("根据id获取设备信息")
    public BaseResult getDeviceById(@RequestBody Device s) {
        BaseResult result = new BaseResult();
        try {
            Device stock = deviceService.queryById(s.getId());
            if (stock != null) {
                result.setCode(ResultApi.successCode);
                result.setMsg(ResultApi.getSuccessMsg);
                result.setData(stock);
            } else {
                result.setCode(ResultApi.failCode);
                result.setMsg(ResultApi.getFailMsg);
            }
        } catch (Exception e) {
            result.setCode(ResultApi.failCode);
            result.setMsg(ResultApi.getFailMsg);
            logger.error("根据id获取设备信息：{}", e.getMessage());
        }
        return result;
    }

    @PostMapping("/getDevicePageList")
    @ApiOperation(value = "设备信息分页")
    public PageInfo<Device> getDevicePageList(@RequestBody DevicePageInput input) {
        PageInfo<Device> pageInfo = new PageInfo<>();
        try {
            pageInfo = deviceService.getDevicePageList(input);
        } catch (Exception e) {
            logger.error("getDevicePageList{}", e.getMessage());
        }
        return pageInfo;
    }

    @PostMapping("/editDevice")
    @ApiOperation("新增或修改设备信息")
    public BaseResult editDevice(HttpSession session, HttpServletRequest request, HttpServletResponse response, @RequestBody Device s) {
        BaseResult result = new BaseResult();
        try {
            Object object = session.getAttribute("outPersonnel");
            if (object == null) {
                response.sendRedirect(request.getContextPath() + "/view/login");
            }
            PersonnelOutput personnel = (PersonnelOutput) object;

            if (s.getId() != 0) {
                if (deviceService.isExist(s) > 0) {
                    result.setCode(ResultApi.failCode);
                    result.setMsg("该设备编号或名称已经存在!");
                    return result;
                }
                int effect = deviceService.update(s);
                if (effect > 0) {
                    result.setCode(ResultApi.successCode);
                    result.setMsg(ResultApi.updateSuccessMsg);
                } else {
                    result.setCode(ResultApi.failCode);
                    result.setMsg(ResultApi.updateFailMsg);
                }
            } else {
                if (deviceService.isExist(s) > 0) {
                    result.setCode(ResultApi.failCode);
                    result.setMsg("该设备编号或名称已经存在!");
                    return result;
                }
                s.setCreateTime(new Date());
                s.setUserId(personnel.getPersonnelId());
                s.setIsDeleted(0);
                int effect = deviceService.insert(s);
                if (effect > 0) {
                    result.setCode(ResultApi.successCode);
                    result.setMsg(ResultApi.addSuccessMsg);
                } else {
                    result.setCode(ResultApi.failCode);
                    result.setMsg(ResultApi.addFailMsg);
                }
            }
        } catch (Exception e) {
            result.setCode(ResultApi.failCode);
            result.setMsg(ResultApi.addFailMsg);
            logger.error("编辑设备出错：{}", e.getMessage());
        }
        return result;
    }

    @PostMapping("/deleteDevice")
    @ApiOperation("删除原料")
    public BaseResult deleteDevice(@RequestBody Device s) {
        BaseResult result = new BaseResult();
        try {
            int iRow = deviceService.deleteById(s.getId());
            if (iRow > 0) {
                result.setCode(ResultApi.successCode);
                result.setMsg(ResultApi.deleteSuccessMsg);
            } else {
                result.setCode(ResultApi.failCode);
                result.setMsg(ResultApi.deleteFailMsg);
            }
        } catch (Exception e) {
            result.setCode(ResultApi.failCode);
            result.setMsg(ResultApi.deleteFailMsg);
            logger.error("删除包材出错：{}", e.getMessage());
        }
        return result;
    }

    @GetMapping("/downDeviceExcelTemplate")
    @ApiOperation("产品导入模版下载")
    public void downStockExcelTemplate(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileName") String fileName) {
        String[] columNames = {"设备编号", "设备名称", "原设备类型", "规格型号","保养周期" ,"供应商","购买日期","安装日期","投产日期","创建时间", "备注"};
        ExcelUtil.download(response, request, fileName, columNames);
    }

    @PostMapping("/deviceImport")
    @ApiOperation("原料信息导入")
    public BaseResult deviceImport(@RequestParam("file") MultipartFile multipartFile, HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        BaseResult baseResult = new BaseResult();
        try {
            Object object = session.getAttribute("outPersonnel");
            if (object == null) {
                response.sendRedirect(request.getContextPath() + "/view/login");
            }
            PersonnelOutput personnel = (PersonnelOutput) object;

            baseResult = this.deviceService.deviceImport(multipartFile,personnel.getPersonnelId());

        } catch (Exception e) {
            logger.error("deviceImport", e.getMessage());
            e.printStackTrace();
        }
        return baseResult;
    }


}
